#include "sqlite_table_widget.h"
#include <QVBoxLayout>
#include <QSqlDatabase>
#include <QCoreApplication>
#include <qdir.h>
#include "plugin_ui_sqlite_global.h"

SqliteTableWidget::SqliteTableWidget(QWidget* parent)
    : QWidget(parent)
{
    initSql();

    m_tableView = new QTableView(this);
    m_model = new QSqlTableModel(this, m_ptr_sqlite_helper->getDatabase());
    m_queryModel = new QSqlQueryModel(this); // 新增
    m_model->setTable(NORMAL_TABLE_NAME);
    m_model->select();

    m_tableView->setModel(m_model);
    m_tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);

    QVBoxLayout* layout = new QVBoxLayout(this);
    layout->addWidget(m_tableView);
    setLayout(layout);
}

SqliteTableWidget::~SqliteTableWidget()
{
    m_ptr_sqlite_helper->close();
    QFile::remove(m_str_db_path);
    qDebug()<<"delete:"<<m_str_db_path;
}

void SqliteTableWidget::setTable(const QString& tableName)
{
    m_model->setTable(tableName);
    m_model->select();
}


void SqliteTableWidget::setQuery(const QString& sql)
{
    m_queryModel->setQuery(sql, m_ptr_sqlite_helper->getDatabase());
    m_tableView->setModel(m_queryModel);
    emit sigSendMsg("sql:" + sql);
}

void SqliteTableWidget::initSql()
{
    //这样 dbPath 会自动用正确的分隔符（Windows 下是 \，Linux 下是 /）
    m_str_db_path = QDir(QCoreApplication::applicationDirPath()).filePath(SQLITE_DB_PATH);
    m_ptr_sqlite_helper = std::make_shared<SqliteHelper>(m_str_db_path);
    m_ptr_sqlite_helper->open();
    m_ptr_sqlite_helper->createTable(CREATE_TABLE_SQL);
    m_ptr_sqlite_helper->execSql(INSERT_TEST_DATA_SQL);

}

